/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Estacionamento.DAOGenerico;

import Estacionamento.DAOEspecifico.DAOCliente;
import Estacionamento.DAOEspecifico.DAOPlano;
import Estacionamento.DAOEspecifico.DAOVeiculo;
import Estacionamento.DAOEspecifico.IDAOCliente;
import Estacionamento.DAOEspecifico.IDAOPlano;
import Estacionamento.DAOEspecifico.IDAOVeiculo;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

/**
 *
 * @author Italo Valença
 */
public abstract class DAOFactory {

    private static EntityManagerFactory factory;
    private static EntityManager entityManager;

    private static IDAOCliente clienteDAO;
    private static IDAOPlano planoDAO;
    private static IDAOVeiculo veiculoDAO;

    public static IDAOCliente getClienteDAO() {
        clienteDAO = new DAOCliente();
        return clienteDAO;
    }

    public static IDAOPlano getPlanoDAO() {
        planoDAO = new DAOPlano();
        return planoDAO;
    }

    public static IDAOVeiculo getVeiculoDAO() {
        veiculoDAO = new DAOVeiculo();
        return veiculoDAO;
    }

    // metodos de gerenciamento
    static {
        factory = Persistence.createEntityManagerFactory("estacionamento");
    }

    public static void close() {
        if (factory != null && factory.isOpen()) {
            factory.close();
        }
    }

    public static EntityManager createEntityManager() {
        if (entityManager == null || !entityManager.isOpen()) {
            entityManager = factory.createEntityManager();
        }
        return entityManager;
    }

    // public static void setEntityManager(EntityManager em){
    // entityManager = em;
    // }
    public static void beginTransaction() {
        if (entityManager != null && entityManager.isOpen()) {
            entityManager.getTransaction().begin();
        }
    }

    public static void commitTransaction() {
        if (entityManager != null && entityManager.isOpen()) {
            entityManager.getTransaction().commit();
        }
    }

    public static void rollback() {
        if (entityManager != null && entityManager.isOpen()) {
            entityManager.getTransaction().rollback();
        }
    }

    public static void closeEntityManager() {
        if (entityManager != null && entityManager.isOpen()) {
            try {
                entityManager.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
